import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Card,
  Divider,
  Modal,
  Badge,
  Button,
} from 'antd';

import { StateType } from './model';
import styles from './style.less';
import '@ant-design/compatible/assets/index.css';

const statusMap:any = ['success', 'default'];
const status = ['使用中', '已禁用'];

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  screen: string;
  loading: boolean;
  PermissionList: StateType;
}

interface TableListState {
  changeWithdrawStatusDialog: boolean;
  fId: number;
  parentId: number;
  withdrawStatus: number;
  current: number;
  pageSize: number;
  prevValues: {
    name: string;
    parent_id: number;
  }[];
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
  partnerWithdrawalAuthPermissionList,
  global: { screen },
  loading,
}: any) => ({
  PermissionList: partnerWithdrawalAuthPermissionList,
  screen,
  loading: loading.effects['partnerWithdrawalAuthPermissionList/fetch'],
}))

class TableList extends React.Component<TableListProps, TableListState> {
  columns = [
    {
      title: '合作商名称',
      dataIndex: 'name',
    },
    {
      title: '状态',
      dataIndex: 'can_withdraw',
      render: (text: number) => <Badge status={statusMap[text - 1]} text={status[text - 1]} />,
    },
    {
      title: '操作时间',
      dataIndex: 'withdraw_oper_time',
      render: (text: string) => text || '--',
    },
    {
      title: '操作人',
      dataIndex: 'withdraw_oper_user_name',
      render: (text: string) => text || '--',
    },
    {
      title: '操作',
      render: (text: any, record: any) => (
        <>
          <span
            className={styles.link}
            onClick={
                () => this.handleShowChangeWithdrawStatusDialog(record.id, record.can_withdraw)
              }
          >
            {record.can_withdraw === 1 ? '禁用' : '启用'}
          </span>
          <Divider type="vertical" />
          <span
            className={record.has_child === 0 ? styles.linkDisabled : styles.link}
            onClick={() => this.handleshowChildList(record)}
          >
            查看
          </span>
        </>
      ),
    },
  ];

  state: TableListState = {
    changeWithdrawStatusDialog: false,
    fId: 0,
    parentId: 0,
    withdrawStatus: 0,
    current: 1,
    pageSize: 20,
    prevValues: [],
    rowId: 0,
  };

  componentDidMount() {
    const { PermissionList: { data } } = this.props;
    if (data?.list?.length) return;

    const { current: pageNum } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'partnerWithdrawalAuthPermissionList/fetch',
      payload: { pageNum },
    });
  }

  /**
   * 打开启用/禁用状态提示框
   */
  handleShowChangeWithdrawStatusDialog = (fId: number, withdrawStatus: number) => {
    this.setState({
      fId,
      withdrawStatus,
      changeWithdrawStatusDialog: true,
    });
  };

  /**
   * 确定启用/禁用状态提示
   */
  handleConfirmChangeWithdrawStatus = () => {
    this.handleHideChangeWithdrawStatusDialog();

    const {
      fId: fcs_id,
      withdrawStatus: can_withdraw_status,
      current: pageNum,
      pageSize: numPerPage,
      parentId: parent_id,
    } = this.state;

    const { dispatch } = this.props;
    dispatch({
      type: 'partnerWithdrawalAuthPermissionList/changeWithdrawStatus',
      payload: {
        pageNum,
        numPerPage,
        parent_id,
        fcs_id,
        can_withdraw_status,
      },
    });
  };

  /**
   * 关闭改变启用/禁用状态提示框
   */
  handleHideChangeWithdrawStatusDialog = () => this.setState({ changeWithdrawStatusDialog: false });

  // 分页
  onSelectChange = (current: number, pageSize: number) => {
    const { parentId: parent_id } = this.state;
    this.setState({ current, pageSize }, () => {
      const { dispatch } = this.props;
      dispatch({
        type: 'partnerWithdrawalAuthPermissionList/fetch',
        payload: {
          pageNum: current,
          numPerPage: pageSize,
          parent_id,
        },
      });
    });
  };

  /**
   * 展示子数据
   */
  handleshowChildList = ({ id, name }: any) => {
    const { current: currentPage, prevValues } = this.state;

    this.setState({
      prevValues: [
        ...prevValues,
        { name, parent_id: id },
      ],
    }, () => {
      const { dispatch } = this.props;
      dispatch({
        type: 'partnerWithdrawalAuthPermissionList/fetch',
        payload: {
          currentPage,
          parent_id: id,
        },
      });
    });

    this.setState({ parentId: id });
  }

  /**
   * 返回查询上一级列表
   */
  handlePrev = () => {
    const { prevValues, current: currentPage } = this.state;
    prevValues.splice(prevValues.length - 1);

    this.setState({ prevValues }, () => {
      const parent_id = prevValues.length > 0
        ? prevValues[prevValues.length - 1].parent_id
        : 0;

      const { dispatch } = this.props;
      dispatch({
        type: 'partnerWithdrawalAuthPermissionList/fetch',
        payload: { currentPage, parent_id },
      });
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  render() {
    const {
      changeWithdrawStatusDialog,
      pageSize,
      current,
      withdrawStatus,
      prevValues,
    } = this.state;

    const {
      PermissionList: { data },
      loading,
    } = this.props;

    const pagination: object = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        onChange: this.onSelectChange,
        showTotal: () => `共${data.count || 0}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onSelectChange,
        showQuickJumper: true,
      }
      : {};

    const dataSource = (data && data.list) || [];

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            {prevValues.length > 0 && (
              <Button
                type="primary"
                size="small"
                className="smallButton"
                onClick={() => this.handlePrev()}
              >
                返回上一级
              </Button>
            )}
            <span style={{ marginLeft: 12 }}>
              {prevValues.length > 0 && prevValues[prevValues.length - 1].name}
            </span>
          </div>
          <Table
            rowKey="id"
            loading={loading}
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          title="确认提示"
          visible={changeWithdrawStatusDialog}
          onOk={this.handleConfirmChangeWithdrawStatus}
          onCancel={this.handleHideChangeWithdrawStatusDialog}
        >
          <p style={{ textAlign: 'center', marginBottom: 0 }}>
            {withdrawStatus === 1 ? '确定禁用此合作商提现权限吗？' : '确定启用此合作商提现权限吗？'}
          </p>
        </Modal>
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
